package cn.memorynine.consumer.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.memorynine.common.tool.CommonTool;
import cn.memorynine.consumer.mapper.ShopManageMapper;
import cn.memorynine.dao.entity.ShopCommodity;
import cn.memorynine.dao.entity.ShopCommodityCatagory;
import cn.memorynine.dao.entity.ShopCommodityCatagoryRelation;
import cn.memorynine.dao.mapper.ShopCommodityCatagoryMapper;
import cn.memorynine.dao.mapper.ShopCommodityCatagoryRelationMapper;
import cn.memorynine.dao.mapper.ShopCommodityMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import cn.memorynine.common.model.ResponseWrapper;
import cn.memorynine.consumer.model.shop.manage.*;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* 管理后台-商城管理服务
* @author 代码生成器
*/
@Slf4j
@Service
public class ShopManageService {

    @Autowired
    private ShopCommodityMapper shopCommodityMapper;

    @Autowired
    private ShopCommodityCatagoryMapper shopCommodityCatagoryMapper;

    @Autowired
    private ShopCommodityCatagoryRelationMapper shopCommodityCatagoryRelationMapper;

    @Autowired
    private ShopManageMapper shopManageMapper;
    /**
     * 1.获取全部商品列表
     * @return
     */
    public ResponseWrapper commodityList(CommodityListParam param){
        //1.准备结果集
        CommodityListResult commodityListResult = new CommodityListResult();

        //2.准备分页参数
        Page<ShopCommodity> pageInfo = new Page<>(param.getPageNum(), param.getNum(),false);

        List<ShopCommodity> shopCommodities;

        //3.获取商品列表
        Integer typeId = param.getTypeId();
        String searchKey = param.getSearchKey();
        if (typeId == -1){
            //3.1类别全查
            //获取商品总数
            commodityListResult.setTotalNum(shopCommodityMapper.selectCount(
                    Wrappers.<ShopCommodity>lambdaQuery()
                            .like(ShopCommodity::getName, searchKey)
            ));
            Page<ShopCommodity> shopCommodityPage = shopCommodityMapper.selectPage(pageInfo,
                    Wrappers.<ShopCommodity>lambdaQuery()
                            .like(ShopCommodity::getName, searchKey)
                            .orderByAsc(ShopCommodity::getStateId)
            );
            shopCommodities = shopCommodityPage.getRecords();
        }else {
            //3.2指定类别查询
            param.setSearchKey("%" + param.getSearchKey() + "%");
            Integer pageNum = (param.getPageNum() - 1) * param.getNum();
            param.setPageNum(pageNum);
            commodityListResult.setTotalNum(shopManageMapper.CountCommodityListByCatagory(param));
            List<Map<String,Object>> commodityList = shopManageMapper.CommodityListByCatagory(param);

            shopCommodities = CommonTool.mapListToBeanList(commodityList, ShopCommodity.class);
        }
        List<CommodityList> commodityLists = new ArrayList<>();
        shopCommodities.forEach(commodity->{
            CommodityList commodityList = new CommodityList();
            BeanUtil.copyProperties(commodity,commodityList);
            commodityList.setIsGround(commodity.getStateId() == 10 ? true : false);
            commodityLists.add(commodityList);
        });
        //查这本书有啥类别
        commodityLists.forEach(commodity->{
            List<Map<String, Object>> maps = shopManageMapper.CatagoryListByCommodity(commodity.getAid());
            List<CommodityCatagoryList> commodityCatagoryLists = CommonTool.mapListToBeanList(maps, CommodityCatagoryList.class);
            commodity.setCommodityCatagoryLists(commodityCatagoryLists);
        });

        //设置结果集
        commodityListResult.setCommodityList(commodityLists);

        //最后一步，返回结果
        return ResponseWrapper.markSuccess(commodityListResult);
    }

    /**
     * 1.1 获取全部商品列表-获取全部类别列表
     * @param param
     * @return
     */
    public ResponseWrapper catagoryList(CatagoryListParam param) {
        List<CatagoryListResult> catagoryListResults = new ArrayList<>();
        catagoryListResults.add(new CatagoryListResult(-1,"全部类别"));
        List<ShopCommodityCatagory> shopCommodityCatagories = shopCommodityCatagoryMapper.selectList(
                Wrappers.<ShopCommodityCatagory>lambdaQuery()
                        .orderByAsc(ShopCommodityCatagory::getIsDelete)
        );
        shopCommodityCatagories.forEach(catagory->{
            CatagoryListResult catagoryListResult = new CatagoryListResult();
            BeanUtil.copyProperties(catagory,catagoryListResult);
            catagoryListResults.add(catagoryListResult);
        });
        return ResponseWrapper.markSuccess(catagoryListResults);
    }

    /**
     * 2.新增/修改商品-商品详情
     * @return
     */
    public ResponseWrapper commodityInfo(CommodityInfoParam param){
        CommodityInfoResult commodityInfoResult = new CommodityInfoResult();

        List<ShopCommodity> shopCommodities = shopCommodityMapper.selectList(
                Wrappers.<ShopCommodity>lambdaQuery()
                        .eq(ShopCommodity::getAid, param.getAid())
        );

        if (!shopCommodities.isEmpty()){
            ShopCommodity shopCommodity = shopCommodities.get(0);
            BeanUtil.copyProperties(shopCommodity,commodityInfoResult);
            commodityInfoResult.setIsGround(shopCommodity.getStateId() == 10 ? true : false);
            //查询该商品的分类列表
            List<Map<String, Object>> maps = shopManageMapper.CatagoryListByCommodityWithChoose(shopCommodity.getAid());
            List<CatagoryListItem> catagoryLists = CommonTool.mapListToBeanList(maps, CatagoryListItem.class);
            commodityInfoResult.setCatagoryList(catagoryLists);
        }

        //最后一步，返回结果
        return ResponseWrapper.markSuccess(commodityInfoResult);
    }

    /**
     * 2.1新增/修改商品-获取商品类别列表
     */
    public ResponseWrapper catagoryListWithChoose(CatagoryListWithChooseParam param) {
        List<CatagoryListWithChooseResult> catagoryListWithChooseResultList = new ArrayList<>();
        List<ShopCommodityCatagory> shopCommodityCatagories = shopCommodityCatagoryMapper.selectList(
                Wrappers.<ShopCommodityCatagory>lambdaQuery()
                        .orderByAsc(ShopCommodityCatagory::getIsDelete)
        );
        shopCommodityCatagories.forEach(catagory->{
            CatagoryListWithChooseResult catagoryListWithChooseResult = new CatagoryListWithChooseResult();
            catagoryListWithChooseResult.setCatagoryAid(catagory.getAid());
            catagoryListWithChooseResult.setCatagoryName(catagory.getName());
            catagoryListWithChooseResult.setIsChoose(false);
            catagoryListWithChooseResultList.add(catagoryListWithChooseResult);
        });
        return ResponseWrapper.markSuccess(catagoryListWithChooseResultList);
    }

    /**
     * 3.新增/修改商品
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper saveCommodityInfo(SaveCommodityInfoParam param){
        ShopCommodity shopCommodity = new ShopCommodity();
        BeanUtil.copyProperties(param,shopCommodity);
        //设置货品上下架状态
        if (param.getIsGround()){
            shopCommodity.setStateId(10);
        } else {
            shopCommodity.setStateId(20);
        }
        if (shopCommodity.getInformation().length() >= 50){
            shopCommodity.setCommodityBrief(shopCommodity.getInformation().substring(0,50)+"...");
        } else {
            shopCommodity.setCommodityBrief(shopCommodity.getInformation());
        }

        if (param.getAid() == -1){
            //新增商品
            shopCommodity.setAid(null);
            shopCommodity.setConsumerAid(param.getTokenConsumerAid());
            shopCommodity.setSale(0);
            shopCommodityMapper.insert(shopCommodity);
        } else {
            //修改商品信息
            shopCommodityMapper.updateById(shopCommodity);
            //删除商品原有分类
            shopCommodityCatagoryRelationMapper.delete(
                    Wrappers.<ShopCommodityCatagoryRelation>lambdaQuery()
                            .eq(ShopCommodityCatagoryRelation::getCommodityAid,shopCommodity.getAid())
            );
        }
        //设置商品的分类
        List<CatagoryList> catagoryList = param.getCatagoryList();
        catagoryList.forEach(catagory->{
            if (catagory.getIsChoose()){
                ShopCommodityCatagoryRelation shopCommodityCatagoryRelation = new ShopCommodityCatagoryRelation();
                shopCommodityCatagoryRelation.setCommodityAid(shopCommodity.getAid());
                shopCommodityCatagoryRelation.setCommodityCatagoryAid(catagory.getCatagoryAid());
                shopCommodityCatagoryRelationMapper.insert(shopCommodityCatagoryRelation);
            }
        });

        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }

    /**
     * 4.上架/下架商品
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper changeCommodity(ChangeCommodityParam param){
        ShopCommodity shopCommodity = new ShopCommodity();
        shopCommodity.setAid(param.getAid());
        if (param.getGround()){
            //上架
            shopCommodity.setStateId(10);
        } else {
            //下架
            shopCommodity.setStateId(20);
        }

        shopCommodityMapper.updateById(shopCommodity);

        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }

    /**
     * 5.获取商品分类列表
     * @return
     */
    public ResponseWrapper commodityTypeList(CommodityTypeListParam param){
        List<CommodityTypeListResult> commodityTypeListResultList = new ArrayList<>();
        List<ShopCommodityCatagory> shopCommodityCatagories = shopCommodityCatagoryMapper.selectList(
                Wrappers.<ShopCommodityCatagory>lambdaQuery()
                        .orderByAsc(ShopCommodityCatagory::getIsDelete)
        );
        shopCommodityCatagories.forEach(catagory->{
            CommodityTypeListResult commodityTypeListResult = new CommodityTypeListResult();
            BeanUtil.copyProperties(catagory,commodityTypeListResult);
            commodityTypeListResultList.add(commodityTypeListResult);
        });

        //最后一步，返回结果
        return ResponseWrapper.markSuccess(commodityTypeListResultList);
    }

    /**
     * 6.新增/修改商品分类
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper saveCommodityType(SaveCommodityTypeParam param){
        ShopCommodityCatagory shopCommodityCatagory = new ShopCommodityCatagory();
        BeanUtil.copyProperties(param,shopCommodityCatagory);
        if (param.getAid() == -1){
            //新增分类
            shopCommodityCatagory.setAid(null);
            shopCommodityCatagoryMapper.insert(shopCommodityCatagory);
        } else {
            shopCommodityCatagoryMapper.updateById(shopCommodityCatagory);
        }

        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }

    /**
     * 7.新增/修改商品分类-商品分类信息
     * @return
     */
    public ResponseWrapper commodityTypeInfo(CommodityTypeInfoParam param){
        CommodityTypeInfoResult commodityTypeInfoResult = new CommodityTypeInfoResult();
        List<ShopCommodityCatagory> shopCommodityCatagories = shopCommodityCatagoryMapper.selectList(
                Wrappers.<ShopCommodityCatagory>lambdaQuery()
                        .eq(ShopCommodityCatagory::getAid, param.getAid())
        );
        if (!shopCommodityCatagories.isEmpty()){
            ShopCommodityCatagory shopCommodityCatagory = shopCommodityCatagories.get(0);
            BeanUtil.copyProperties(shopCommodityCatagory,commodityTypeInfoResult);
        }
        //最后一步，返回结果
        return ResponseWrapper.markSuccess(commodityTypeInfoResult);
    }

    /**
     * 8.删除/恢复商品分类
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper delCommodityType(DelCommodityTypeParam param){
        ShopCommodityCatagory shopCommodityCatagory = new ShopCommodityCatagory();
        BeanUtil.copyProperties(param,shopCommodityCatagory);
        shopCommodityCatagoryMapper.updateById(shopCommodityCatagory);

        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }


}